package iotwisp.school.user.entity;

import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

import iotwisp.school.user.command.role.ChangeRoleEnableSCmd;
import iotwisp.school.user.command.role.CreateRoleSCmd;
import iotwisp.school.user.command.role.ModifyRoleSCmd;
import iotwisp.base.orm.StringIdBaseEntity;
import iotwisp.base.util.UUIDGenerator;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.Type;

import iotwisp.school.user.qo.RoleQO;

/**
 * {@link RoleQO} {@link diance.view.organization.vo.RoleVO}
 * {@link diance.view.organization.provider.qo.RoleViewQO}
 * {@link jzjd.organization.service.RoleService} {@link RoleSPI} Role RoleQO
 * RoleVO RoleSPI RoleViewSPI RoleService RoleViewService RoleController
 * RoleViewController
 *
 * @author yuxx
 */
//@Data
//@EqualsAndHashCode(callSuper = false)
@DynamicUpdate
@Entity
@Table(name = M.TABLE_PREFIX + "role")
@SuppressWarnings("serial")
public class Role extends StringIdBaseEntity {

	/**
	 * 系统角色名称
	 */
	@Column(name = "name")
	private String name;

	/**
	 * 角色是否启用
	 */
	@Type(type = "yes_no")
	@Column(name = "enable")
	private Boolean enable;

	/**
	 * 拥有的权限集
	 */
	@ManyToMany(fetch = FetchType.LAZY)
	@Cascade({ org.hibernate.annotations.CascadeType.SAVE_UPDATE })
	@JoinTable(name = "org_role_permission_link", joinColumns = { @JoinColumn(name = "role_id") }, inverseJoinColumns = {
			@JoinColumn(name = "permission_id") })
	private Set<Permission> permissionSet;

	/**
	 * 归属的用户集
	 */
	@ManyToMany(mappedBy = "roleSet", fetch = FetchType.LAZY)
	private Set<Admin> adminSet;

	public void create(CreateRoleSCmd cmd, Set<Permission> permissionSet) {

		setId(UUIDGenerator.getUUID());
		setName(cmd.getName());
		setEnable(cmd.getEnable());
		setPermissionSet(permissionSet);
	}

	public void modify(ModifyRoleSCmd cmd) {

		setName(cmd.getName());
		setEnable(cmd.getEnable());
	}

	public void changeEnable(ChangeRoleEnableSCmd cmd) {
		if ((cmd.getEnable() == null)) {
			setEnable(!getEnable());
		} else {
			setEnable(cmd.getEnable());
		}
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Boolean getEnable() {
		return enable;
	}

	public void setEnable(Boolean enable) {
		this.enable = enable;
	}

	public Set<Permission> getPermissionSet() {
		return permissionSet;
	}

	public void setPermissionSet(Set<Permission> permissionSet) {
		this.permissionSet = permissionSet;
	}

	public Set<Admin> getAdminSet() {
		return adminSet;
	}

	public void setAdminSet(Set<Admin> adminSet) {
		this.adminSet = adminSet;
	}
}
